﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ExaminationSys.DataAccess;
using ExaminationSys.DataAccess.Entity;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.Helper;
using Ext.Net;


namespace ExaminationSys.View.Paper
{
    public partial class PaperDetailFixedChosenList : System.Web.UI.Page
    {
 

        private static readonly PaperSubjectQuestionService Proxy = ObjectFactory<PaperSubjectQuestionService>.Create();


        public string PaperID { get { return Request.QueryString["PaperID"] != null ? Request.QueryString["PaperID"].ToString() : string.Empty; } }
        public string Title { get { return Request.QueryString["Title"] != null ? Request.QueryString["Title"].ToString() : string.Empty; } }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
                PageEntity = null;
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            lblTitle.Text = Title;
        }

        private int pageSize = 20;
        public static PageEntity PageEntity = null;
        protected void StorePaperSubjectQuestion_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            string sqlWhere = " 1=1";
            int pageIndex = 0;
            if (PageEntity != null)
            {
                sqlWhere = PageEntity.SqlWhere;
                pageIndex = 1;
            }
            else
            {
                sqlWhere += " and PaperID ='" + new Guid(PaperID) + "'";
                pageIndex = (e.Start / e.Limit) + 1;

            }

            int totalPage, totalRecord;
            this.StorePaperSubjectQuestion.DataSource = Proxy.GetListByPage(sqlWhere, " OrderIndex ", pageSize, pageIndex,
                                                                   out totalPage, out totalRecord);
            e.Total = totalRecord;

            this.StorePaperSubjectQuestion.DataBind();
        }

        public void SearchFun(PageEntity pageEntity)
        {
            PageEntity = pageEntity;
        }


        protected void Command(object sender, DirectEventArgs e)
        {
            var command = e.ExtraParams["command"];

            var id = e.ExtraParams["Id"];
            if (string.IsNullOrWhiteSpace(id))
            {
                MessageBoxHelper.ShowInfo("获取ID失败");
                return;
            }

            if (command.Equals("edit", StringComparison.OrdinalIgnoreCase))
            {
               // ShowDetails(id);
            }
            else
            {
                var entity = Proxy.Get(new Guid(id));
                if (entity != null)
                {
                    entity.Status = 0;
                    var success = Proxy.Update(entity);
                    if (success)
                    {
                        StorePaperSubjectQuestion.Remove(entity.ID);
                        MessageBoxHelper.ShowInfo("删除成功");
                    }
                }
            }
        }
 
        [DirectMethod]
        public void DoConfirm()
        {
            RowSelectionModel sm = GridPanelPaperSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }
            X.Msg.Confirm("提示", "是否删除选中记录?", new MessageBoxButtonsConfig
            {
                Yes = new MessageBoxButtonConfig
                {
                    Handler = "X.DoDelete()",
                    Text = "是"
                },
                No = new MessageBoxButtonConfig
                {
                    Text = "否"
                }
            }).Show();
        }

        [DirectMethod]
        public void DoDelete()
        {
            RowSelectionModel sm = GridPanelPaperSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }

            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Delete(ids);
            if (success)
            {
                ids.ForEach(id => StorePaperSubjectQuestion.Remove(id));
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void BatchDelete_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelPaperSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要删除的记录");
                return;
            }

            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Delete(ids);
            if (success)
            {
                ids.ForEach(id => StorePaperSubjectQuestion.Remove(id));

                //删除后，重新生成OrderIndex
                  var qustionlist = Proxy.GetQuestionList(new Guid(PaperID));
                  if (qustionlist != null && qustionlist.Count > 0)
                  {
                      var templist = qustionlist.OrderBy(o => o.OrderIndex).ToList();
                      for (var i = 0; i < templist.Count; i++)
                      {
                          templist[i].OrderIndex = i + 1;
                          Proxy.Update(templist[i]);
                      }
                     
                  }
                  StorePaperSubjectQuestion.Reload();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }
        protected void BatchLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelPaperSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要锁定的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Lock(ids, 1);
            if (success)
            {
                StorePaperSubjectQuestion.Reload();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }

        protected void BatchUnLock_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelPaperSubjectQuestion.SelectionModel.Primary as RowSelectionModel;

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要解锁的记录");
                return;
            }
            List<string> ids = new List<string>();
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }
            var success = Proxy.Lock(ids, 0);
            if (success)
            {
                StorePaperSubjectQuestion.Reload();
                MessageBoxHelper.ShowInfo("保存成功");
            }
        }


        //跳转到选题界面
        protected void BtnGo_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect("PaperDetailFixedList.aspx?PaperID=" + PaperID + "&Title=" + Title);

        }

        //跳转到试卷管理界面
        protected void BtnGoManage_Click(object sender, DirectEventArgs e)
        {
            Response.Redirect("PaperInfoList.aspx");

        }

        //高级查找
        protected void BtnMoveTo_Click(object sender, DirectEventArgs e)
        {
            RowSelectionModel sm = GridPanelPaperSubjectQuestion.SelectionModel.Primary as RowSelectionModel;
            List<string> ids = new List<string>();

            int step = Convert.ToInt32(Step.Value);
            if (step == 0)
            {
                MessageBoxHelper.ShowWarning("请填写您想移动的步数，[负数向前移，正数向后移]。");
                return;
             }

            if (sm.SelectedRows.Count == 0)
            {
                MessageBoxHelper.ShowWarning("请选择要移动的题目！");
                return;
            }
            foreach (var row in sm.SelectedRows)
            {
                ids.Add(row.RecordID);
            }

            if (ids.Count > 1)
            {
                MessageBoxHelper.ShowWarning("目前只支持一道题目的移动！");
                return;
            }

            var setResult = Proxy.SetPaperQuestionOrderIndex(new Guid(ids[0]), new Guid(PaperID), step);

            if (setResult < 0)
            {
                if (step > 0)
                {
                    MessageBoxHelper.ShowWarning("您选择向后移动步数太大！");
                }
                else
                {
                    MessageBoxHelper.ShowWarning("您选择向前移动步数太大！");
                }
                return;
            }
           
            StorePaperSubjectQuestion.Reload();
        }
        
        
        protected void BtnFind_Click(object sender, DirectEventArgs e)
        {
            var text = string.Empty;//SearchText.Text.Trim();
            StringBuilder sqlWhere = new StringBuilder(" Status<>0 ");
            if (!string.IsNullOrWhiteSpace(text))
            {
                text = text.SqlSafe();
                StringBuilder sbWhere = new StringBuilder(" and ");
                sbWhere.Append(" (UserID like '%{0}%' ");
                sbWhere.Append(" or LoginID like '%{0}%' ");
                sbWhere.Append(" or UserName like '%{0}%' ");
                sbWhere.Append(" or CollegeName like '%{0}%' ");
                sbWhere.Append(" or MajorName like '%{0}%') ");
                sqlWhere.Append(string.Format(sbWhere.ToString(), text));
            }
            PageEntity pageEntity = new PageEntity();
            pageEntity.SqlWhere = sqlWhere.ToString();
            SearchFun(pageEntity);
            StorePaperSubjectQuestion.Reload();
        }

        public void Btn_GoBack(object sender, DirectEventArgs e)
        {
            Response.Redirect("PaperInfoList.aspx");
        }

    }
}